package cn.project.engineering.ui

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import cn.project.engineering.R
import cn.project.engineering.base.MyAppCompatActivity
import cn.project.engineering.http.HttpClient
import cn.project.engineering.http.RequestCallback
import cn.project.engineering.http.bean.*
import cn.project.engineering.service.LoopJobService
import cn.project.engineering.ui.adapter.FileDistributionDapter
import cn.project.engineering.ui.adapter.StationListDistributionDapter
import cn.project.engineering.ui.view.WonderfulDialog
import cn.project.engineering.utils.AppUtils
import cn.project.engineering.utils.DialogCallback
import cn.project.engineering.utils.IpAddressUtils
import cn.project.engineering.utils.toast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.google.gson.Gson
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.android.synthetic.main.activity_distribution.*
import log.KLog
import org.json.JSONArray
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

class DistributionActivity : MyAppCompatActivity() {
    companion object {
        private const val TAG = "DistributionActivity"
    }

    lateinit var filervAdapter:FileDistributionDapter
    lateinit var filervData:MutableList<SerchDistributionInfo>


    lateinit var stationrvAdapter:StationListDistributionDapter
    lateinit var stationData:MutableList<StationInfo>


     var fileImageBanner:ArrayList<String > = ArrayList()
    var  fileNoCurrent=""
    var  fileNameCurrent=""

    var PartNO="M000001"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_distribution)
        initview();
        initdata()
        
    }

    override fun netWork(isnet: Boolean) {

    }

    private fun initdata() {

    }

    private fun initview() {
        titlebar.leftView.setOnClickListener {
            finish()
        }
        thingnum.setOnClickListener {
            HttpClient.httpService().searchThingNum(MacIP = IpAddressUtils.getMacAddress(), SelectPre = "true").enqueue(object : RequestCallback<ArrayList<ThingInfo>> {
                override fun onRequestSuccess(body: ArrayList<ThingInfo>?) {
                    body?.let {
                        if (it.isEmpty())
                            return
                        WonderfulDialog.listDialog(this@DistributionActivity,object :DialogCallback{
                            override fun confirm(value: String?) {
                                thingnum.setText(value)
                                PartNO= value!!
                                getStataList(state = "false")

                                //parno 板号
                                HttpClient.httpService().fileDistribution(PartNO = PartNO).enqueue(object : RequestCallback<MutableList<SerchDistributionInfo>> {
                                    override fun onRequestSuccess(body: MutableList<SerchDistributionInfo>?) {
                                        body?.let {
                                            if (it.size==0)
                                                return
                                            filervAdapter.setNewData(it)
                                            fileImageBanner.clear()
                                            val bannerInfo = filervAdapter.data.get(0)
                                            val pages = try {
                                                bannerInfo.Pages.toInt()
                                            } catch (e: NumberFormatException) {
                                                1
                                            }
                                            for (i in 1 until pages) {
                                                fileImageBanner.add("${bannerInfo.ImgUrl}/${bannerInfo.WOID}$${i}.png")
                                            }
                                            KLog.d(TAG, fileImageBanner.toString())
                                            file_show.setDatas(fileImageBanner as List<Nothing>?)
                                            fileNameCurrent=bannerInfo.FileName
                                            fileNoCurrent=bannerInfo.FileNO

                                        }

                                    }

                                    override fun onRequestFail(error: RequestError) {

                                    }

                                })

                            }

                            override fun cancel() {
                            }
                        },it)

                    }

                }

                override fun onRequestFail(error: RequestError) {

                }

            })
        }

//多文件
// 遍历 工位 是否有分配过文件  文件编码  工位
        distribution_button.setOnClickListener {
            val realCount = file_show.currentItem+1
            val data = stationrvAdapter.data;
            KLog.d(TAG, data.toString())
            //工位
            var currentStationNo=""
            for (i in 0 until  data.size){
                var stationInfo = data.get(i)
                if (stationInfo.Choose){
                    currentStationNo=stationInfo.FNumber
                    //有无分配过
                    for(j in 0 until  data.size){
                        if (j==i){
                            continue
                        }
                        val get = data.get(j)
                        if (currentStationNo==get.FNumber){
                            if (fileNoCurrent==get.FileNO){
                                toast("此工位已分配此文件")
                                return@setOnClickListener
                            }
                        }
                    }
                    if (fileNoCurrent==stationInfo.FileNO){
                        if (stationInfo.CurrentPage.contains(""+realCount)){
                            toast("此页已分配")
                        }else{
                            if (TextUtils.isEmpty(stationInfo.CurrentPage)){
                                stationInfo.CurrentPage=""+realCount
                            }else{
                                stationInfo.CurrentPage=stationInfo.CurrentPage+","+realCount
                            }
                            stationInfo.CurrentFileName=fileNameCurrent
                            stationInfo.FileNO=fileNoCurrent
                        }
                    }else{
                        if (TextUtils.isEmpty(stationInfo.CurrentPage)){
                            stationInfo.CurrentPage=""+realCount
                        }else{
                            stationInfo.CurrentPage=""+realCount
                        }
                        stationInfo.CurrentFileName=fileNameCurrent
                        stationInfo.FileNO=fileNoCurrent
                    }

                }

            }
            KLog.d(TAG, data.toString())
            stationrvAdapter.setDiffNewData(data)
            stationrvAdapter.notifyDataSetChanged()

        }
        start_play.setOnClickListener {
            val data = stationrvAdapter.data
            val  jsonArray=JSONArray()
            for (i in 0 until  data.size){
                var hashMap= HashMap<String,String>()
                val date = data.get(i)
                hashMap["Choose"]="false"
                hashMap["FNumber"]=""+date.FNumber
                hashMap["CurrentFileName"]=""+date.CurrentFileName
                hashMap["CurrentPage"]=""+date.CurrentPage
                hashMap["FileNO"]=""+date.FileNO
                hashMap["LineNO"]=""+date.LineNO
                jsonArray.put(hashMap)
            }
            var  gson=Gson()
            var  json:String= gson.toJson(jsonArray)
            json=json.replace("{\"values\":","")
            json=json.substring(0,json.length-1)

            HttpClient.httpService().playDistribution(PartNO=PartNO,json = json).enqueue(object : RequestCallback<String> {
                override fun onRequestSuccess(body:String?) {
                    body?.let {

                                toast(it)
                    }

                }

                override fun onRequestFail(error: RequestError) {

                }

            })
        }
        stop_play.setOnClickListener {
            val data = stationrvAdapter.data
            val  jsonArray=JSONArray()
            for (i in 0 until  data.size){
                var hashMap= HashMap<String,String>()
                val date = data.get(i)
                hashMap["Choose"]="false"
                hashMap["FNumber"]=""+date.FNumber
                hashMap["CurrentFileName"]=""+date.CurrentFileName
                hashMap["CurrentPage"]=""+date.CurrentPage
                hashMap["FileNO"]=""+date.FileNO
                hashMap["LineNO"]=""+date.LineNO
                jsonArray.put(hashMap)
                date.CurrentFileName=""
                date.CurrentPage=""
                date.FileNO=""
            }
            var  gson=Gson()
            var  json:String= gson.toJson(jsonArray)
            json=json.replace("{\"values\":","")
            json=json.substring(0,json.length-1)
            HttpClient.httpService().stopDistribution(json = json).enqueue(object : RequestCallback<String> {
                override fun onRequestSuccess(body:String?) {
                    body?.let {
                        stationrvAdapter.setNewData(data)
                        stationrvAdapter.notifyDataSetChanged()
                        toast(it)
                    }

                }

                override fun onRequestFail(error: RequestError) {

                }

            })
        }
        filervData=ArrayList()
        filervAdapter= FileDistributionDapter(R.layout.item_distribution_file,filervData)
        filerv.layoutManager= LinearLayoutManager(this)
        filerv.adapter=filervAdapter

            stationData=ArrayList()
            stationrvAdapter= StationListDistributionDapter(R.layout.distribution_station,stationData)
            station_rv.layoutManager= LinearLayoutManager(this)
            station_rv.adapter=stationrvAdapter

        file_show.adapter = object : BannerImageAdapter<String>(fileImageBanner) {
            override fun onBindView(holder: BannerImageHolder, data: String?, position: Int, size: Int) {
                Glide.with(this@DistributionActivity)
                        .load(fileImageBanner[position])
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(holder.imageView)
            }

            override fun onCreateHolder(parent: ViewGroup?, viewType: Int): BannerImageHolder {
                val imageView = ImageView(this@DistributionActivity)
                // 注意，必须设置为match_parent，这个是viewpager2强制要求的
                val params = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
                imageView.layoutParams = params
                imageView.scaleType = ImageView.ScaleType.FIT_XY
                return BannerImageHolder(imageView)
            }
        }
        file_show.viewPager2.offscreenPageLimit=2
        file_show.isAutoLoop(false)


        filervAdapter.setOnItemClickListener { adapter, view, position ->
            fileImageBanner.clear()
             val bannerInfo = filervAdapter.data.get(position)
            val pages = try {
                bannerInfo.Pages.toInt()
            } catch (e: NumberFormatException) {
                1
            }
            for (i in 1 until pages) {
                fileImageBanner.add("${bannerInfo.ImgUrl}/${bannerInfo.WOID}$${i}.png")
            }
            KLog.d(TAG, fileImageBanner.toString())
            file_show.setDatas(fileImageBanner as List<Nothing>?)
            fileNameCurrent=bannerInfo.FileName
            fileNoCurrent=bannerInfo.FileNO

        }

        pre_distribution_check.setOnClickListener {
            getStataList(""+pre_distribution_check.isChecked)
        }
    }

    fun  getStataList(state:String){
        HttpClient.httpService().stationList(MacIP = IpAddressUtils.getMacAddress(),SelectPre = state,PartNO = PartNO).enqueue(object : RequestCallback<MutableList<StationInfo>> {
            override fun onRequestSuccess(body: MutableList<StationInfo>?) {
                body?.let {

                    stationrvAdapter.setNewData(it)
                }

            }

            override fun onRequestFail(error: RequestError) {

            }

        })
    }
}